package com.xuhui.xuaiagent.Advisor;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.advisor.api.AdvisedRequest;
import org.springframework.ai.chat.client.advisor.api.AdvisedResponse;
import org.springframework.ai.chat.client.advisor.api.CallAroundAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAroundAdvisorChain;
import org.springframework.ai.chat.client.advisor.api.StreamAroundAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAroundAdvisorChain;
import org.springframework.ai.chat.model.MessageAggregator;


/**
 * @author 21829
 */
@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {


	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}

	@Override
	public int getOrder() {
		return 0;
	}

	private AdvisedRequest before(AdvisedRequest request) {
//		logger.debug("request: {}", this.requestToString.apply(request));
		log.info("用户输入信息:{}",request.userText());
		return request;
	}

	private void observeAfter(AdvisedResponse advisedResponse) {
//		logger.debug("response: {}", this.responseToString.apply(advisedResponse.response()));
		log.info("ai 大模型返回信息:{}",advisedResponse.response().getResult().getOutput().getText());
	}

	@Override
	public String toString() {
		return MyLoggerAdvisor.class.getSimpleName();
	}
	//用于处理同步请求和响应
	@Override
	public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
		//调用某个顾问前先去执行当前类中的before方法
		advisedRequest = before(advisedRequest);
		//调用下一个顾问的方法
		AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
		//执行完后获取响应对ai大模型的响应进行操作
		observeAfter(advisedResponse);
		//返回响应
		return advisedResponse;
	}
	//用于处理流式请求和响应
	@Override
	public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {

		advisedRequest = before(advisedRequest);

		Flux<AdvisedResponse> advisedResponses = chain.nextAroundStream(advisedRequest);

		return new MessageAggregator().aggregateAdvisedResponse(advisedResponses, this::observeAfter);
	}

}
